#!/usr/bin/env bash
scriptVersion="1.6"
scriptName="AutoExtras"


#### Import Settings
source /config/extended.conf
#### Import Functions
source /config/extended/functions
#### Create Log File
logfileSetup

verifyConfig () {
  if [ "$enableExtras" != "true" ]; then
	log "Script is not enabled, enable by setting enableExtras to \"true\" by modifying the \"/config/extended.conf\" config file..."
	log "Sleeping (infinity)"
	sleep infinity
  fi

  if [ -z "$autoExtrasScriptInterval" ]; then
    autoExtrasScriptInterval="24h"
  fi
}

AutoExtrasProcess () {
 
  sonarrSeriesList=$(curl -s --header "X-Api-Key:"${arrApiKey} --request GET  "$arrUrl/api/v3/series")
  sonarrSeriesTotal=$(echo "${sonarrSeriesList}"  | jq -r '.[].id' | wc -l)
  sonarrSeriesIds=$(echo "${sonarrSeriesList}" | jq -r '.[].id')
  
  loopCount=0
  for id in $(echo $sonarrSeriesIds); do
      loopCount=$(( $loopCount + 1 ))
      arrSeriesData="$(echo "$sonarrSeriesList" | jq -r ".[] | select(.id==$id)")"
      arrSeriesPath="$(echo "$arrSeriesData" | jq -r ".path")"
      arrSeriesTitle="$(echo "$arrSeriesData" | jq -r ".title")"
      if [ -d "$arrSeriesPath" ]; then
        log "$loopCount of $sonarrSeriesTotal :: $id :: $arrSeriesTitle :: Processing with Extras.bash"
        bash /config/extended/Extras.bash "$id"
      else
        log "$loopCount of $sonarrSeriesTotal :: $id :: $arrSeriesTitle :: Series folder does not exist, skipping..."
        continue
      fi
  done
}

for (( ; ; )); do
	let i++
	logfileSetup
	log "Script starting..."
    	verifyConfig
	getArrAppInfo
	verifyApiAccess
	AutoExtrasProcess
	log "Script sleeping for $autoExtrasScriptInterval..."
	sleep $autoExtrasScriptInterval
done

exit
